package com.example.temp.utils;

import java.security.MessageDigest;
import java.security.SecureRandom;

public class PasswordHasher {

    // 生成随机盐
    public static String generateSalt() {
        SecureRandom random = new SecureRandom();
        byte[] salt = new byte[16];
        random.nextBytes(salt);
        return bytesToHex(salt);
    }

    // 将字节数组转换为十六进制字符串
    private static String bytesToHex(byte[] bytes) {
        StringBuilder result = new StringBuilder();
        for (byte b : bytes) {
            result.append(String.format("%02x", b));
        }
        return result.toString();
    }

    // 将十六进制字符串转换为字节数组
    private static byte[] hexToBytes(String hex) {
        byte[] bytes = new byte[hex.length() / 2];
        for (int i = 0; i < bytes.length; i++) {
            bytes[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16);
        }
        return bytes;
    }

    public static boolean verifyPassword(String inputPassword, String storedHash, String storedSalt) {
        // 使用存储的盐和哈希算法对用户输入的密码进行哈希
        String inputHash = hashPassword(inputPassword, storedSalt);

        // 将用户输入的哈希与存储的密码哈希进行比较
        return inputHash.equals(storedHash);
    }


    // 使用盐和SHA-256哈希函数加密密码
    public static String hashPassword(String password, String salt) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            byte[] saltBytes = hexToBytes(salt);
            md.update(saltBytes);
            byte[] passwordBytes = password.getBytes("UTF-8");
            md.update(passwordBytes);
            byte[] hash = md.digest();
            return bytesToHex(hash);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }



}
